package licode.unisop.realm.application.service;

import licode.unisop.provider.vo.SiPageResult;
import licode.unisop.provider.vo.SiUser;
import licode.unisop.unilite.result.UniException;
import licode.unisop.unilite.result.UniResultCode;

import java.util.function.Supplier;

/**
 * 实现Url远程调用的公共类
 *
 * @author licode
 */
public class SiUrlCallBase {
    public static final String CALL_VERSION = "1.0";

    private String url;
    private SiRestfulCallUtil siRestfulCallUtil;

    private static class SiUserPageResult extends SiPageResult<SiUser> {}

    public static String execFeign(Supplier<SiMethodReturn> m) {
        SiMethodReturn result;

        try {
            result = m.get();
        } catch (Exception ignore) {
            result = new SiMethodReturn();
            result.setCode(UniResultCode.INVALID_SERVER_ERROR.code());
            result.setMessage(UniResultCode.INVALID_SERVER_ERROR.message());
        }

        if (0 != result.getCode()) {
            throw new UniException(result.getCode(), result.getMessage());
        }
        return result.getResult();
    }

    public SiUrlCallBase(SiRestfulCallUtil callUtil, String url) {
        this.url = url;
        this.siRestfulCallUtil = callUtil;
    }

    protected String execute(String method, String params) {
        return SiUrlCallBase.execFeign(() ->
                siRestfulCallUtil.post(null, SiMethodReturn.class, SiMethodCall.builder()
                        .version(CALL_VERSION)
                        .method(method)
                        .params(params)
                        .build(), url));
    }
}
